package machine.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import machine.bean.City;
import machine.bean.Weather;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * 和风天气api
 *
 * @author zhanghui145
 * @date 2021/12/25 13:47
 * @since 1.0.0
 */
@Service
public class WeatherApi {

    private static final String WEATHER_URI =
            "https://devapi.qweather.com/v7/weather/now?key=" +
                    "  &location=";

    private static final String CITY_URI =
            "https://geoapi.qweather.com/v2/city/lookup?key=" +
                    "  &location=";

    public Weather getWeatherByLocation(String cityName){
        String cityId = getCityId(cityName).getId();
        HttpResponse response =HttpRequest.get(WEATHER_URI + cityId).execute();
        return JSONUtil.parse(response.body()).toBean(Weather.class);
    }

    private City getCityId(String cityName){
        HttpResponse response =HttpRequest.get(CITY_URI + cityName).execute();
        String cityStr = response.body();
        JSONArray array = JSONUtil.parseArray(JSONUtil.parseObj(cityStr).get("location"));
        Assert.isTrue(!array.isEmpty(), "城市名查不到~");
        Object city = array.get(0);
        return JSONUtil.parse(city).toBean(City.class);
    }
}